package com.xc.smart.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import com.xc.smart.entity.Img;
import com.xc.smart.mapper.ImgMapper;
import com.xc.smart.utlis.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.*;

/**
 * 上傳
 *
 * @author admin
 */
@Slf4j
@RestController
@RequestMapping("/up")
public class UploadController {

    @Autowired
    ImgMapper imgMapper;

    @Value("${web.upload-path}")
    private  String path;

    @RequestMapping(value="/upload",method= RequestMethod.POST)
    @ResponseBody
    public R upload(MultipartFile file){
        String date = DateUtil.formatDate(new Date());
        if (!file.isEmpty()) {
            long size = file.getSize() / 1024;
            String storePath= path+"/"+date;
            String fileName = date+file.getOriginalFilename();
            File filepath = new File(storePath, fileName);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            try {
                file.transferTo(new File(storePath+File.separator+fileName));
                if(size > 1024){
                    ImgUtil.scale(
                            FileUtil.file(storePath+File.separator+fileName),
                            FileUtil.file(storePath+File.separator+fileName),
                            0.8f
                    );
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.error();
            }
            imgMapper.insert(new Img(file.getOriginalFilename(),"/"+date+"/"+fileName,"def"));
            return R.ok().put("url","/"+date+"/"+fileName);
        }else {
            return R.error();
        }
    }


}
